/**
 * Copyright (C), 2013-2019, 中商惠民科技有限公司
 * FileName: 反射
 * FileName: 反射
 * Author:   Eilen
 * Date:     2019/4/23 17:28
 * Description: 反射的相关知识点
 * History:
 * <author>          <time>          <version>          <desc>
 **/
package com.algorithm.basic;


import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 〈describe〉<br>
 * 〈反射的相关知识点〉
 *
 * @author Eilen
 * @create 2019/4/23
 * @since 1.0.0
 */
public class 反射 {


    public static void main(String[] args) throws Exception {
        //反射获取私有方法();
        //获取构造方法();
        //get私有属性();
        //反射获取对象();
    }

    /**
     * 反射获取私有方法
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private static void 反射获取私有方法() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> forName = Class.forName("com.algorithm.basic.Book");
        Method method = forName.getDeclaredMethod("declaredMethod", int.class);
        method.setAccessible(true);
        Object instance = forName.newInstance();
        String invoke = (String) method.invoke(instance, 0);
        System.out.println(invoke);
    }

    private static void 获取构造方法() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
        //反射获取构造方法
        Class<?> forName = Class.forName("com.algorithm.basic.Book");
        Constructor<?> constructor = forName.getDeclaredConstructor(String.class, String.class);
        constructor.setAccessible(true);
        Object o = constructor.newInstance("你好吗", "我很好");
        Book book = (Book) o;
        System.out.println(JSONObject.toJSONString(book));
    }

    private static void 反射获取对象() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        //反射创建对象
        Class<?> aClass = Class.forName("com.algorithm.basic.Book");
        Book book = (Book) aClass.newInstance();
        book.setName("小白");
        book.setAuthor("你好");
        System.out.println(JSONObject.toJSONString(book));
    }

    //反射获取私有属性
    private static void get私有属性() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> name = Class.forName("com.algorithm.basic.Book");
        Object o = name.newInstance();
        Field tag = name.getDeclaredField("TAG");//通过反射获取类中指定私有属性
        tag.setAccessible(true);//调用该类是私有的（private）的情况下需要设置为true 不然会报异常
        String s = (String) tag.get(o);
        System.out.println(s);
    }
}
